import React from 'react';
import Grid from '../../components/table/grid';
import {Link} from 'react-router-dom';
import {
    Input,
    Button,
    Row,
    Col,
    Form,
    Select,
    Divider,
    message,
    Modal,
    InputNumber,
    Popconfirm,
    Dropdown,
    Icon,
    Menu,
    Spin
} from 'antd';
import axios from 'axios';
import CollectionCreateForm from './modifyStaffForm';
import ChargeHisModle from './chargeHisModle';
import Discount from './discount';
import RechargeHis from './rechargeHis'
import '../login/login.css';
import {injectIntl} from 'react-intl';
import DepartmentPicker from '../../components/pickCity/departmentPicker';
import AuthButton from '../../components/auth/authButton'
const FormItem = Form.Item;
const createForm = Form.create;

class staffManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            visible4charge: false,
            visible4maxChargeNum: false,
            visible4chargeHis: false,
            visible4rechargeHis: false,
            visible4discount: false,
            charge4all: false,
            loading: false,
            amount: 10,
            maxChargeNum: 1,
            id: '',
            accountIds: [],
            selectAccount: {},
            params: {
                account: ``,
                name: ``
            },
            refresh: 0
        };
        const common = this.props.intl.messages.common;
        this.columns = [
            {
                title: common.username,
                dataIndex: 'account',
                key: 'account',
                width: 150
            },
            {
                title: common.staffName,
                dataIndex: 'name',
                key: 'name',
                width: 150
            },
            {
                title: common.belongDep,
                dataIndex: 'levelOne',
                key: 'levelOne',
                width: 150
            },
            {
                title: common.belongDep,
                dataIndex: 'levelTwo',
                key: 'levelTwo',
                width: 150
            },
            {
                title: common.belongDep,
                dataIndex: 'levelThree',
                key: 'levelThree',
                width: 150
            },
            {
                title: common.AddTime,
                dataIndex: 'registTime',
                key: 'registTime',
                width: 150
            },
            {
                title: common.cardNo,
                dataIndex: 'cardNo',
                key: 'cardNo',
                width: 150
            },
            {
                title: common.balance,
                dataIndex: 'amount',
                key: 'amount',
                width: 150,
                render: (text, record) => (
                    <span>
                            {this.getAmount(record.amount)}
                    </span>
                )
            },
            {
                title: common.totalAmount,
                dataIndex: 'totalAmount',
                key: 'totalAmount',
                width: 150,
                render: (text, record) => (
                    <span>
                            {this.getTotalAmount(record.totalAmount)}
                    </span>
                )
            },
            {
                title: common.maxChargeNum,
                dataIndex: 'maxChargeNum',
                key: 'maxChargeNum',
                width: 150
            },
            {
                title: common.status,
                dataIndex: 'status',
                key: 'status',
                width: 150
            },
            {
                title: common.operation,
                key: 'action',
                width: 180,
                fixed: 'right',
                render: (text, record) => (
                    <span>
                        <span data-auth="007001006">
                        <a onClick={() => this.modifyStaff(text, record)}>{common.modify}</a>
                        <Divider type="vertical"/>
                        </span>
                        <Popconfirm placement="top" title={common.VerifyPerformed} okText={common.sure}
                                    onConfirm={() => this.modStatus(text, record)}
                                    cancelText={common.cancel}>
                            <span data-auth="007001007">
                            <a>
                                {((record) => {
                                    if (record.status === common.normal) {
                                        return common.forbidden
                                    }
                                    if (record.status === common.forbidden) {
                                        return common.enabled
                                    }
                                })(record)}
                            </a>
                            <Divider type="vertical"/>
                            </span>
                        </Popconfirm>
                        {/*<Divider type="vertical"/>*/}
                        {/*<Popconfirm placement="top" title="确认需要删除吗？" okText="确认" onConfirm={() => this.deleteStaff(text, record)}*/}
                        {/*cancelText="取消">*/}
                        {/*<a>删除</a>*/}
                        {/*</Popconfirm>*/}
                        <Dropdown overlay={(
                            <Menu>
                                <Menu.Item>
                                    <Popconfirm placement="top" title={common.DoResetIt} okText={common.sure}
                                                onConfirm={() => this.resetPass(text, record)}
                                                cancelText={common.cancel}>
                                        <a>{common.resetPassword}</a>
                                    </Popconfirm>
                                </Menu.Item>
                                <Menu.Item>
                                    <a onClick={() => this.chargeHis(text, record)}>{common.chargeHis}</a>
                                </Menu.Item>
                                <Menu.Item>
                                    <a onClick={() => this.rechargeHis(text, record)}>{common.rechargeHis}</a>
                                </Menu.Item>
                                <Menu.Item>
                                    <a onClick={() => this.modMaxChargeNum(text, record)}>{common.maxChargeNum}</a>
                                </Menu.Item>
                                <Menu.Item>
                                    <a onClick={() => this.discount(text, record)}>{common.setDiscount}</a>
                                </Menu.Item>
                            </Menu>
                        )}>
                            <a data-auth="007001013">
                                {common.more} <Icon type="down"/>
                            </a>
                        </Dropdown>
                    </span>
                )
            }
        ];
    }

    getAmount(amount) {
        if (amount == undefined || amount == null || amount == '') {
            return 0;
        } else {
            return amount;
        }
    }

    getTotalAmount(totalAmount) {
        if (totalAmount == undefined || totalAmount == null || totalAmount == '') {
            return 0;
        } else {
            return totalAmount;
        }
    }

    modStatus = (text) => {
        const common = this.props.intl.messages.common;
        console.log("text", text);
        let params = {
            id: text.id,
            status: text.status === common.forbidden ? 2 : 3
        }
        axios.post('/api/user/stat/mod', {...params}).then(res => {
            if (res && res.code == 200) {
                if (res.data == 1) {
                    message.success(common.OperateSuccessfully)
                    this.setState({
                        refresh: this.state.refresh + 1
                    })
                } else {
                    message.error(common.operateFailure)
                }
            }
        })

    }
    //最大充电数
    modMaxChargeNum = (text) => {
        this.setState({
            visible4maxChargeNum: true,
            selectAccount: text,
        });
    }
    //关闭最大充电数弹框
    closeMaxChargeNum = () => {
        this.setState({
            visible4maxChargeNum: false,
        });
    }
    //改变最大充电数
    ChargeNum = (value) => {
        this.setState(Object.assign(this.state.selectAccount, {maxChargeNum: value}));
    }
    //提交最大充电书
    subMaxChargeNum = () => {
        let params = {
            id: this.state.selectAccount.id,
            maxChargeNum: this.state.selectAccount.maxChargeNum
        }
        axios.post('/api/user/modMaxChargeNum', {...params}).then(res => {
            if (res && res.code == 200) {
                this.setState({
                    visible4maxChargeNum: false,
                });
            }
        })

    }

    //充电记录
    chargeHis = (text) => {
        this.setState({
            visible4chargeHis: true,
            selectAccount: text,
        });
    };
    //关闭充值记录窗口
    closeChargeHis = () => {
        this.setState({
            visible4chargeHis: false,
        });
    }
    rechargeHis = (text) => {
        this.setState({
            visible4rechargeHis: true,
            selectAccount: text,
        });
    }

    closeRechargeHis = () => {
        this.setState({
            visible4rechargeHis: false,
        });
    }

    //修改员工
    modifyStaff = (text) => {
        this.setState({
            id: text.id,
            visible: true,
            selectAccount: text
        });

    }
    //删除员工
    deleteStaff = (text, record) => {
        let params = {
            id: text.id,
        }
        axios.post('/api/user/del', {...params}).then(res => {
            if (res && res.code == 200) {
                message.success(res.data);
                this.setState({
                    refresh: this.state.refresh + 1
                })
            }
        })
    }
    //重置密码
    resetPass = (text, record) => {
        console.log(text);
        const common = this.props.intl.messages.common;
        let params = {
            id: text.id,
        }
        axios.post('api/user/restPwd', {...params}).then(res => {
            if (res && res.code == 200) {
                if (res.data == 1) {
                    message.success(`${common.resetPasswordSuc}
                    默认密码：123456`);
                }
                if (res.data == 0) {
                    message.error(common.resetPasswordFailure);
                }
                // this.setState({
                //     refresh: this.state.refresh + 1
                // })
            }
        })
    }

    //表格提交
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                return;
            }
            this.setState({
                params: {...values},
                refresh: this.state.refresh + 1
            });
            // this.setState(Object.assign(this.state.params,values))
        });
    }

    //接口数据转换
    transformData = (data) => {
        const common = this.props.intl.messages.common;
        data.forEach((item) => {
            if (item.status == 1) {
                item.status = common.waitConfirm
            } else if (item.status == 2) {
                item.status = common.normal
            } else if (item.status == 3) {
                item.status = common.forbidden
            }
        });
        return data
    };
    //充值按钮
    onChange = (value) => {
        console.log(value)
        this.setState({
            amount: value,
        });
    }
    hideModal = () => {
        this.setState({
            visible4charge: false,
        });
    };
    rechargeLog = () => {
        if (this.state.charge4all) {
            //所有
            this.setState({
                loading: true
            })
            axios.post('/api/user/rechargeLog/addAll', {...{amount: this.state.amount}}).then(res => {
                if (res && res.code == 200) {
                    this.setState({
                        visible4charge: false,
                        refresh: this.state.refresh + 1,
                        loading: false
                    });
                }
            })
        } else {
            //批量
            let params = {
                amount: this.state.amount,
                accountIds: this.state.accountIds.toString(),
            }
            axios.post('/api/user/rechargeLog/add', {...params}).then(res => {
                if (res && res.code == 200) {
                    this.setState({
                        visible4charge: false,
                        refresh: this.state.refresh + 1
                    });
                }
            })
        }
    };
    //修改数据
    saveFormRef = (formRef) => {
        this.formRef = formRef;
    };
    handleCancel = () => {
        this.setState({visible: false});
        this.formRef.props.form.resetFields()
    };
    handleCreate = () => {
        const form = this.formRef.props.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            values.id = this.state.id;
            axios.post('/api/user/mod', {...values}).then(res => {
                if (res && res.code == 200) {
                    this.setState({
                        visible: false,
                        refresh: this.state.refresh + 1
                    });
                    form.resetFields()
                }
            })
        });
    }

    //打开折扣弹框
    discount = (text) => {
        this.setState({
            visible4discount: true,
            selectAccount: text,
        });
    }
    //关闭折扣弹框
    closeDiscount = () => {
        //清空
        this.setState({
            visible4discount: false
        })
        const form = this.discountForm.props.form;
        form.resetFields();
    }

    handleDiscount = () => {
        const form = this.discountForm.props.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            // console.log(this.state.selectAccount.id)
            values.id = this.state.selectAccount.id;
            delete values.account;
            axios.post('/api/user/dsc/mod', {...values}).then(res => {
                if (res && res.code == 200) {
                    this.setState({
                        visible4discount: false,
                        refresh: this.state.refresh + 1
                    });
                }
            })
        });
    }
    saveDiscount = (formRef) => {
        this.discountForm = formRef;
    }

    render() {
        const common = this.props.intl.messages.common;
        const token = JSON.parse(sessionStorage.getItem("token")).token;
        const locale = JSON.parse(sessionStorage.getItem("locale")).saveValue;
        console.log('locale', locale);
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    accountIds: selectedRowKeys
                })
            },
        };
        const {getFieldDecorator} = this.props.form;

        const marginRight8 = {
            marginRight: 8
        }
        return (
            <AuthButton>
                <div>
                    {/*---------------修改密码--------------------*/}
                    <CollectionCreateForm
                        wrappedComponentRef={this.saveFormRef}
                        visible={this.state.visible}
                        onCancel={this.handleCancel}
                        onCreate={this.handleCreate}
                        selectAccount={this.state.selectAccount}
                    />
                    {/*---------------金额充值--------------------*/}
                    <Modal
                        title={common.rechargeAmountUnit}
                        visible={this.state.visible4charge}
                        onOk={this.rechargeLog}
                        onCancel={this.hideModal}
                        okText={common.sure}
                        cancelText={common.cancel}
                    >
                        <Spin spinning={this.state.loading}>
                            <span style={{paddingRight: '10px'}}>{common.rechargeAmountUnit}：</span>
                            <InputNumber size="large" max={10000} defaultValue={this.state.amount}
                                         onChange={this.onChange}/>
                        </Spin>
                    </Modal>
                    {/*---------------充电记录--------------------*/}
                    <ChargeHisModle
                        visible={this.state.visible4chargeHis}
                        onCancel={this.closeChargeHis}
                        account={this.state.selectAccount}
                    />

                    {/*---------------充值记录--------------------*/}
                    <RechargeHis
                        visible={this.state.visible4rechargeHis}
                        onCancel={this.closeRechargeHis}
                        account={this.state.selectAccount}
                    />

                    {/*---------------最大充电数--------------------*/}
                    <Modal
                        title={common.maxChargeNum}
                        visible={this.state.visible4maxChargeNum}
                        onOk={this.subMaxChargeNum}
                        onCancel={this.closeMaxChargeNum}
                        okText={common.modify}
                        cancelText={common.cancel}
                    >
                        <span style={{paddingRight: '10px'}}>{common.maxChargeNum}：</span>
                        <InputNumber size="large" max={10000} onChange={this.ChargeNum}
                                     value={this.state.selectAccount.maxChargeNum}/>
                    </Modal>

                    {/*---------------折扣设置--------------------*/}
                    <Discount
                        wrappedComponentRef={this.saveDiscount}
                        visible={this.state.visible4discount}
                        onCancel={this.closeDiscount}
                        onCreate={this.handleDiscount}
                        account={this.state.selectAccount}
                    />

                    <div>
                        <form form={this.props.form} className={'SC-form'}>
                            <Row gutter={16}>
                                <Col xxl={3} xl={4}>
                                    <FormItem
                                    >
                                        {getFieldDecorator('account')(
                                            <Input placeholder={common.PleaseEnterUserName}/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col xxl={3} xl={4}>
                                    <FormItem
                                    >
                                        {getFieldDecorator('name')(
                                            <Input placeholder={common.PleaseEnterStaffName}/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col xxl={3} xl={4}>
                                    <FormItem
                                    >
                                        {getFieldDecorator('org')(
                                            <DepartmentPicker placeholder={common.department}/>
                                        )}
                                    </FormItem>
                                </Col>
                                <Col xxl={15} xl={12}>
                                    <FormItem>
                                        <Button type="primary" className="ant-btn-84"
                                                onClick={this.handleSubmit}
                                                style={marginRight8}>{common.search}</Button>
                                        <Link to="/staff/addStaff">
                                            <Button type="primary" style={marginRight8} data-auth={'007001002'}
                                                    className="ant-btn-84">{common.addStaff}</Button>
                                        </Link>
                                        <Button type="primary" className="ant-btn-84"
                                                data-auth="007001003"
                                                style={marginRight8} onClick={() => {
                                            if (this.state.accountIds.length == 0) {
                                                message.success(common.pleaseSelectEmployeesFirst);
                                                return
                                            }
                                            this.setState({visible4charge: true, charge4all: false})
                                        }}>{common.recharge}</Button>
                                        <Button type="primary" className="ant-btn-84"
                                                data-auth="007001004"
                                                style={marginRight8} onClick={() => {
                                            this.setState({visible4charge: true, charge4all: true})
                                        }}>{common.recharge4all}</Button>
                                        <a href={`${axios.defaults.baseURL}/api/user/export?account=${this.state.params.account ? this.state.params.account : ''}&name=${this.state.params.name ? this.state.params.name : ''}&token=${token}&locale=${locale}`}>
                                            <Button type="primary"
                                                    className="ant-btn-84">{common.exportStatement}</Button>
                                        </a>
                                    </FormItem>
                                </Col>
                            </Row>
                        </form>
                    </div>
                    <Grid rowSelection={rowSelection} transformData={this.transformData} refresh={this.state.refresh}
                          params={this.state.params} columns={this.columns} url="api/user/qry"/>
                </div>
            </AuthButton>

        )
    }

}

staffManage = createForm()(staffManage);
export default injectIntl(staffManage);
